package com.gzsz.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(
        urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "encoding", value = "UTF-8")
        }
)
public class CharseterEncodingFilter implements Filter {
    private String encoding = "UTF-8"; // 默认编码

    @Override
    public void init(FilterConfig config) throws ServletException {
        // 从 FilterConfig 中读取初始化参数
        String encodingParam = config.getInitParameter("encoding");
        if (encodingParam != null) {
            encoding = encodingParam;
        }
        System.out.println("Filter initialized with encoding: " + encoding);
    }

    @Override
    public void destroy() {
        // 清理资源（如果有）
        System.out.println("Filter destroyed");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 设置请求和响应的编码
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=UTF-8");
        // 继续后续的过滤器链或目标资源
        chain.doFilter(request, response);
    }
}